﻿using System;

using netaddICTs.Umb.ProtectedMedia.Business.IO;

using umbraco.BusinessLogic;
using umbraco.cms.businesslogic;
using umbraco.cms.businesslogic.media;

namespace netaddICTs.Umb.ProtectedMedia.Business.EventHandlers {

    /// <summary>
    /// Handles inheriting of permissions settings for new 'Protected Folders'.
    /// </summary>
    public class InheritPermissions : ApplicationBase {

        public InheritPermissions() {
            Media.New += OnMediaNew;   
        }

        /// <summary>
        /// Handles the New event on media items.
        /// Media item will inherits group permission settings from parent folder if parent media item is of 'Protected Folder' type
        /// </summary>
        /// <param name="sender">Media item that fires the event</param>
        /// <param name="e">An instance of <see cref="DeleteEventArgs"/>DeleteEventArgs</param>
        private static void OnMediaNew(Media sender, NewEventArgs e){
            Media parentMediaItem;
            
            //Find parent media item if it does exist
            try {
                parentMediaItem = new Media(sender.Parent.Id);
            } catch {
                return;
            }

            //Check media item's type
            if (string.Compare(sender.ContentType.Alias, Configuration.ProtectedMedia.Instance.Aliases.ProtectedFolderAlias.UmbracoAlias, true) != 0) return;

            //Check parent media item's type
            if (parentMediaItem.ContentType.Alias != Configuration.ProtectedMedia.Instance.Aliases.ProtectedFolderAlias.UmbracoAlias) return;

            //Get name of group permission alias from config
            var permissionsAlias = Configuration.ProtectedMedia.Instance.Aliases.PermissionAlias.UmbracoAlias;

            //Copy group permission settings from parent media item
            sender.getProperty(permissionsAlias).Value = parentMediaItem.getProperty(permissionsAlias).Value;
        }
    }
}